"""
    Controller for rds-report printing.
    Utility like as MassAction.
"""

import cherrypy
from turbogears import expose, widgets, validate
from mnemoply.reports import reports
from mnemoply.controllers.containers import Container
from mnemoply.utils import IdsValidator

class ReportsController(Container):
    def _get_item(self, name):
        try:
            return reports.byTag(name)
        except KeyError:
            return None

    @expose()
    def generate(self, report, **kw):
        fields = report.fields[:]

        ### Special workaround for ids list
        ### Yes, it IS a hack
        ### In the future we can try to hide
        ### all already validated fields
        # We want to display incorrect ids field and
        # hide correct
        def index(_list, predicate):
            for i, x in enumerate(_list):
                if predicate(x):
                    return i
            return None

        ids_index = index(fields, lambda x: x.name == "ids")

        if ids_index is not None:
            try:
                IdsValidator.to_python(kw['ids'])
                ids_field_type = widgets.HiddenField
            except:
                ids_field_type = widgets.TextField

            fields[ids_index] = ids_field_type(
                name="ids",
                validator=IdsValidator,
                label=_("IDs"),
            )
        ### End of the hack

        report_form = widgets.TableForm(
            name="report_form",
            fields=fields,
        )

        @validate(form=report_form)
        def validated_generate(report, tg_errors=None, **args):
            if tg_errors is not None:
                return dict(
                    tg_template="genshi:mnemoply.templates.lib.report_params",
                    report=report,
                    form=report_form,
                )

            result = report.run(args)

            cherrypy.response.headerMap['Content-Type'] = report.outputType
            cherrypy.response.headerMap['Content-Disposition'] = \
                "filename=\"report-%s.rds\"" % report.tag

            return result
        return validated_generate(report, **kw)
    generate.expose_object = True

    @expose()
    def index(self):
        return '- none -'

exposed = ReportsController()

def generate(report_name, **kw):
    kw = dict([(k, str(v)) for k, v in kw.items()])

    raise cherrypy.InternalRedirect(
        '/Report/%s/generate' % report_name, kw
    )
